#include "lm_sys.h"
#include <time.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include "lm_color.h"
#include "../common/lm_log.h"
#include "../common/lm_error.h"


/**
 * @brief trap callback funtion, it will exit window.
 * 
 * @param sig: signal flag
 * 
 * @return none
*/
static void trap(int sig)
{
    if (sig == SIGINT) {
        endwin();
        exit(0);
    }
}

void lm_sys_exit(int flag)
{
    endwin();
    exit(flag);
}

/**
 * @brief initialize system console, you should call it firstly.
 * 
 * @param: none
 * 
 * @return 0: 
*/
int lm_sys_console_init(void)
{
    //system("chcp 65001 >null");  UTF-8 
    //system("chcp 936 >null");    GBK

    #if (_WIN32)
        system("chcp 437 >null");   // US ASCII
        //system("chcp 65001 >null");  //UTF-8 
        //system("chcp 936 >null");   // GBK
        system("del null");   // delete null file

    #elif ( __linux__)
        system("linux command to set 437 page code >/dev/null");   // US ASCII
    #else
        #error Unknow host OS type!
    #endif

    time_t seed;
    initscr();
    seed = time((time_t *)0);
    srand(seed);
    start_color();

# if defined(NCURSES_VERSION) || (defined(PDC_BUILD) && PDC_BUILD > 3000)
    use_default_colors();
# endif

    cbreak();
    noecho();
    curs_set(0);

#if !defined(__TURBOC__) && !defined(OS2)
    signal(SIGINT, trap);
#endif

    noecho();

    /* refresh stdscr so that reading from it will not cause it to
       overwrite the other windows that are being created */
    refresh();

    /* Create the main window */
    if(LINES < 12 || COLS < 12) {
        LM_LOG_ERROR("The console size is too small");
        endwin();
        return LM_ERR;
    }

    //reset cursor on 0 position
    curs_set(0);

    lm_init_palette();

    return LM_OK;
}
